package com.mgq.juc.design.guard.v2;

/**
 * @author MaGuangQi
 * @description
 * @date 2021-12-16 10:37
 **/
public class GuardedObject {
    public int getId() {
        return id;
    }

    /**
     * id,用来表示guardObject
     */
    private int id;
    /**
     * 返回对象
     */
    private Object response;

    public GuardedObject(int id) {
        this.id = id;
    }

    public Object get() {
        synchronized (this) {
            while (response == null) {
                //一直等待 结果
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

    /**
     * 带超时的get()方法
     * 处理完时间-开始时间 >=timeout时,就应该返回
     *
     * @param timeout
     * @return
     */
    public Object get(long timeout) {
        synchronized (this) {
            long startTime = System.currentTimeMillis();
            //记录经过多长时间
            long passedTime = 0;
            while (response == null) {
                //达到时间了,直接终止
                long waitTime = timeout - passedTime;
                if (waitTime <= 0) {
                    break;
                }
                try {
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                long endTime = System.currentTimeMillis();
                passedTime = endTime - startTime;
            }

        }
        return response;
    }

    public void complete(Object response) {
        this.response = response;
        synchronized (this) {
            //通知线程
            this.notifyAll();
        }
    }

}
